package org.example.memora.service.serviceImpl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.example.memora.common.result.Result;
import org.example.memora.entity.Post;
import org.example.memora.entity.PostCollect;
import org.example.memora.mapper.PostCollectMapper;
import org.example.memora.service.PostCollectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.example.memora.common.result.PageResult;
import java.time.Instant;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class PostCollectServiceImpl implements PostCollectService {

    @Autowired
    private PostCollectMapper postCollectMapper;

    @Transactional
    @Override
    public Result<?> collectPost(Long userId, String postId) {
        // 检查是否已收藏
        PostCollect exist = postCollectMapper.selectByUserAndPost(userId, postId);
        if (exist != null) {
            return Result.error("已收藏，不能重复收藏");
        }
        // 新建收藏记录
        PostCollect record = new PostCollect();
        record.setUserId(userId);
        record.setPostId(postId);
        record.setCreatedAt(Instant.now());
        postCollectMapper.insertCollect(record);
        return Result.success(1, "收藏成功");
    }

    @Transactional
    @Override
    public Result<?> uncollectPost(Long userId, String postId) {
        // 检查是否存在收藏记录
        PostCollect exist = postCollectMapper.selectByUserAndPost(userId, postId);
        if (exist == null) {
            return Result.error("未收藏，无法取消收藏");
        }
        postCollectMapper.deleteCollect(userId, postId);
        return Result.success(1, "取消收藏成功");
    }

    @Override
    public boolean hasCollected(Long userId, String postId) {
        PostCollect exist = postCollectMapper.selectByUserAndPost(userId, postId);
        return exist != null;
    }
    @Override
    public PageResult getCollectPosts(Long userId, Integer pageNum, Integer pageSize) {
        // 计算分页偏移量
        int offset = (pageNum - 1) * pageSize;

        // 查询当前页收藏的帖子列表
        List<Post> posts = postCollectMapper.selectCollectedPostsByUser(userId, offset, pageSize);

        // 查询该用户的总收藏数量
        long total = postCollectMapper.countCollectedPostsByUser(userId);

        return new PageResult((int)total, posts);
    }

}
